<?php

namespace app\controllers;
use yii\data\ActiveDataProvider;
use Yii;
use app\models\user;
use yii\filters\auth\QueryParamAuth;

class OrderController extends \yii\rest\ActiveController
{
	public $modelClass = 'app\models\Order';


	public function behaviors()
    {
        return \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            //响应返回json
            'contentNegotiator' => [
                'formats' => [
                    'application/json' => \yii\web\Response::FORMAT_JSON,
                ],
            ],
            //接口采用参数带token的方式进行认证 
            'authenticator' => [
            'class' => QueryParamAuth::className(),
            
            ],
    ]);
    }

	public $serializer = [
         'class' => 'yii\rest\Serializer',
         'collectionEnvelope' => 'items'
     ];


     public function actionTj()
     {

        if (!isset($_POST["car_number"])||!isset($_POST["user_id"]))
         { throw new \yii\web\HttpException(400, '请填写正确的参数！');}

try {
            $caruser =User::findOne([
     'id' => $_POST["user_id"]
         ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
       if($caruser==null)
        throw new \yii\web\HttpException(400, '对不起，没有这个用户！');


         $model = new $this->modelClass;
         $model->attributes = Yii::$app->request->post();
       
         $model->save();
         if (! $model->save()) {
             return array_values($model->getFirstErrors())[0];
         }
        return $model;
     }

     //自定义的search方法

    public function actionSearch()
    {
    if (isset($_POST["user_id"])) {
        $model = new $this->modelClass;
        $query = $model::find()
        ->where(['user_id' => $_POST["user_id"]]);
        try {
            $provider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => false
            ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
        if ($provider->getCount() <= 0) {
            throw new \yii\web\HttpException(404, '没有找到结果');
        } else {
            return $provider;
        }
    } else {
        throw new \yii\web\HttpException(400, '请输入正确的参数！');
               
          }
       }

}
